package org.example.videotran.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.example.videotran.exception.AppException;
import org.example.videotran.exception.AppExceptionCodeMsg;
import org.example.videotran.utils.JwtToken;

import java.io.IOException;

@WebFilter(filterName = "jwtAuthenticationFilter", urlPatterns = "/api/*")
public class JwtAuthenticationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String method = ((HttpServletRequest) request).getMethod();

        if ("OPTIONS".equals(method)){
            // 允许预检请求直接通过，不进行 Token 验证
            chain.doFilter(request, response);
            return;
        }

        String token = httpRequest.getHeader("token");

        if (token != null) {
            String phone = JwtToken.extractPhone(token);

            if (phone != null && JwtToken.validateToken(token, phone)) {
                // 这里可以设置 SecurityContext 或其他认证机制
                System.out.println("Token is valid. User: " + phone);
            } else {
                throw new AppException(AppExceptionCodeMsg.OVERDUE_TOKEN);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.NULL_TOKEN);
        }

        chain.doFilter(request, response);

    }


    @Override
    public void destroy() {
    }
}

